import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Input,
  Select,
  Modal,
  Form,
  message,
  Tooltip,
  Popconfirm,
  Badge,
  Typography,
  Row,
  Col,
  Descriptions,
  Divider,
  DatePicker,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  BugOutlined,
  ToolOutlined,
  QuestionCircleOutlined,
  RiseOutlined,
  ClockCircleOutlined,
  UserOutlined,
  ReloadOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  SyncOutlined,
  StopOutlined,
  SearchOutlined,
  SettingOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Search } = Input;
const { Option } = Select;
const { Text, Title } = Typography;

interface Ticket {
  id: string;
  title: string;
  description: string;
  type: 'bug' | 'feature' | 'support' | 'improvement';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  status: 'open' | 'in_progress' | 'resolved' | 'closed';
  assignee?: string;
  reporter: string;
  createdAt: string;
  updatedAt: string;
}

interface Assignee {
  id: string;
  name: string;
}

const PlatformTickets: React.FC = () => {
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [assignees, setAssignees] = useState<Assignee[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [priorityFilter, setPriorityFilter] = useState<string>('all');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);
  const [form] = Form.useForm();

  // Mock data
  const mockTickets: Ticket[] = [
    {
      id: 'T-001',
      title: '登录页面无法正常显示',
      description: '用户反馈登录页面在Chrome浏览器中无法正常显示，页面布局错乱',
      type: 'bug',
      priority: 'high',
      status: 'open',
      assignee: 'A001',
      reporter: '张三',
      createdAt: '2024-01-15 09:30:00',
      updatedAt: '2024-01-15 09:30:00'
    },
    {
      id: 'T-002',
      title: '新增用户权限管理功能',
      description: '需要在系统中新增用户权限管理功能，支持角色分配和权限控制',
      type: 'feature',
      priority: 'medium',
      status: 'in_progress',
      assignee: 'A002',
      reporter: '王五',
      createdAt: '2024-01-14 14:20:00',
      updatedAt: '2024-01-15 08:45:00'
    },
    {
      id: 'T-003',
      title: '数据导出功能优化',
      description: '优化现有的数据导出功能，提高导出速度和稳定性',
      type: 'improvement',
      priority: 'low',
      status: 'resolved',
      assignee: 'A003',
      reporter: '孙七',
      createdAt: '2024-01-10 11:15:00',
      updatedAt: '2024-01-14 16:30:00'
    },
    {
      id: 'T-004',
      title: '系统部署问题咨询',
      description: '客户咨询系统在生产环境的部署配置问题',
      type: 'support',
      priority: 'urgent',
      status: 'open',
      reporter: '客户A',
      createdAt: '2024-01-15 16:45:00',
      updatedAt: '2024-01-15 16:45:00'
    }
  ];

  const mockAssignees: Assignee[] = [
    { id: 'A001', name: '李四' },
    { id: 'A002', name: '赵六' },
    { id: 'A003', name: '周八' }
  ];

  useEffect(() => {
    setTickets(mockTickets);
    setAssignees(mockAssignees);
  }, []);

  const getTypeText = (type: string) => {
    const typeMap = {
      bug: '缺陷',
      feature: '功能',
      support: '支持',
      improvement: '改进'
    };
    return typeMap[type as keyof typeof typeMap] || type;
  };

  const getTypeIcon = (type: string) => {
    const iconMap = {
      bug: <BugOutlined />,
      feature: <ToolOutlined />,
      support: <QuestionCircleOutlined />,
      improvement: <RiseOutlined />
    };
    return iconMap[type as keyof typeof iconMap] || <QuestionCircleOutlined />;
  };

  const getStatusText = (status: string) => {
    const statusMap = {
      open: '待处理',
      in_progress: '处理中',
      resolved: '已解决',
      closed: '已关闭'
    };
    return statusMap[status as keyof typeof statusMap] || status;
  };

  const getPriorityColor = (priority: string) => {
    const colorMap = {
      low: 'green',
      medium: 'blue',
      high: 'orange',
      urgent: 'red'
    };
    return colorMap[priority as keyof typeof colorMap] || 'default';
  };

  const getStatusColor = (status: string) => {
    const colorMap = {
      open: 'red',
      in_progress: 'blue',
      resolved: 'green',
      closed: 'default'
    };
    return colorMap[status as keyof typeof colorMap] || 'default';
  };

  const getStatusIcon = (status: string) => {
    const iconMap = {
      open: 'error',
      in_progress: 'processing',
      resolved: 'success',
      closed: 'default'
    };
    return iconMap[status as keyof typeof iconMap] || 'default';
  };

  const getStatusBadgeIcon = (status: string) => {
    switch (status) {
      case 'open':
        return 'default';
      case 'in_progress':
        return 'processing';
      case 'resolved':
        return 'success';
      case 'closed':
        return 'error';
      default:
        return 'default';
    }
  };

  const handleView = (record: Ticket) => {
    setSelectedTicket(record);
    setIsModalVisible(true);
  };

  const handleEdit = (record: Ticket) => {
    setSelectedTicket(record);
    form.setFieldsValue({
      ...record,
      assignee: record.assignee || undefined
    });
    setIsModalVisible(true);
  };

  const handleModalOk = () => {
    form.validateFields().then(values => {
      if (selectedTicket) {
        const updatedTickets = tickets.map(ticket => 
          ticket.id === selectedTicket.id 
            ? { ...ticket, ...values, updatedAt: new Date().toISOString() }
            : ticket
        );
        setTickets(updatedTickets);
        message.success('工单更新成功');
      }
      setIsModalVisible(false);
      setSelectedTicket(null);
      form.resetFields();
    });
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    setSelectedTicket(null);
    form.resetFields();
  };

  const filteredTickets = tickets.filter(ticket => {
    const matchesSearch = ticket.title.toLowerCase().includes(searchText.toLowerCase()) ||
                         ticket.description.toLowerCase().includes(searchText.toLowerCase());
    const matchesStatus = statusFilter === 'all' || ticket.status === statusFilter;
    const matchesPriority = priorityFilter === 'all' || ticket.priority === priorityFilter;
    return matchesSearch && matchesStatus && matchesPriority;
  });

  const columns: ColumnsType<Ticket> = [
    {
      title: '工单信息',
      key: 'ticketInfo',
      width: 250,
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: 4 }}>
            {getTypeIcon(record.type)}
            <span style={{ marginLeft: 8 }}>{record.title}</span>
          </div>
          <Text type="secondary" style={{ fontSize: 12 }}>
            {record.id}
          </Text>
        </div>
      ),
    },
    {
      title: '类型/优先级',
      key: 'typeAndPriority',
      width: 140,
      render: (_, record) => (
        <Space direction="vertical" size="small">
          <Tag color="blue">{getTypeText(record.type)}</Tag>
          <Tag color={getPriorityColor(record.priority)}>
            {record.priority.toUpperCase()}
          </Tag>
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Badge 
          status={getStatusIcon(status) as any} 
          text={getStatusText(status)}
        />
      ),
    },
    {
      title: '处理信息',
      key: 'assigneeInfo',
      width: 150,
      render: (_, record) => {
        const assignee = assignees.find(a => a.id === record.assignee);
        return (
          <div>
            <div style={{ marginBottom: 4 }}>
              <UserOutlined style={{ marginRight: 4, color: '#1890ff' }} />
              {assignee ? assignee.name : '未分配'}
            </div>
            <Text type="secondary" style={{ fontSize: 12 }}>
              报告人: {record.reporter}
            </Text>
          </div>
        );
      },
    },
    {
      title: '时间信息',
      key: 'timeInfo',
      width: 180,
      render: (_, record) => (
        <div>
          <div style={{ fontSize: '12px', color: '#666', marginBottom: 2 }}>
            <ClockCircleOutlined style={{ marginRight: 4 }} />
            创建: {new Date(record.createdAt).toLocaleString('zh-CN')}
          </div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            更新: {new Date(record.updatedAt).toLocaleString('zh-CN')}
          </div>
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
            style={{ color: '#1890ff' }}
          >
            详情
          </Button>
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            style={{ color: '#52c41a' }}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 工单管理表格 */}
      <Card bodyStyle={{ padding: 0 }}>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Title level={4} style={{ margin: 0, color: '#262626' }}>
            <ToolOutlined style={{ marginRight: 8 }} />
            工单管理
          </Title>
          <Space>
            <Search
              placeholder="搜索工单标题或描述"
              allowClear
              style={{ width: 300 }}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
            />
            <Select
              value={statusFilter}
              onChange={setStatusFilter}
              style={{ width: 120 }}
            >
              <Option value="all">全部状态</Option>
              <Option value="open">待处理</Option>
              <Option value="in_progress">处理中</Option>
              <Option value="resolved">已解决</Option>
              <Option value="closed">已关闭</Option>
            </Select>
            <Select
              value={priorityFilter}
              onChange={setPriorityFilter}
              style={{ width: 120 }}
            >
              <Option value="all">全部优先级</Option>
              <Option value="low">低</Option>
              <Option value="medium">中</Option>
              <Option value="high">高</Option>
              <Option value="urgent">紧急</Option>
            </Select>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {}}
              style={{ borderRadius: 6 }}
            >
              新建工单
            </Button>
            <Button 
              icon={<ReloadOutlined />}
              onClick={() => {}}
              loading={loading}
            >
              刷新
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={filteredTickets}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            total: filteredTickets.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
        />
      </Card>

      <Modal
        title={
          <div style={{ fontSize: 18, fontWeight: 600, color: '#262626' }}>
            <ToolOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            {selectedTicket ? '工单详情' : '新建工单'}
          </div>
        }
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={650}
        styles={{
          header: {
            paddingBottom: 8
          },
          body: {
            padding: '12px 16px'
          }
        }}
      >
        {selectedTicket && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {/* 工单信息卡片 */}
            <Card 
              size="small" 
              style={{ 
                borderRadius: 8,
                boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02)'
              }}
            >
              <div style={{ marginBottom: 8 }}>
                <Title level={4} style={{ 
                  margin: 0, 
                  display: 'flex', 
                  alignItems: 'center', 
                  gap: 8,
                  color: '#262626',
                  fontSize: 18
                }}>
                  {getTypeIcon(selectedTicket.type)}
                  {selectedTicket.title}
                </Title>
                <Text type="secondary" style={{ fontSize: 14 }}>#{selectedTicket.id}</Text>
              </div>
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: 12, 
                flexWrap: 'wrap',
                marginBottom: 12
              }}>
                <Badge 
                  status={getStatusIcon(selectedTicket.status) as any} 
                  text={getStatusText(selectedTicket.status)}
                  style={{ fontSize: 13 }}
                />
                <Tag color="blue" style={{ fontSize: 12, padding: '2px 8px' }}>
                  {getTypeText(selectedTicket.type)}
                </Tag>
                <Tag color={getPriorityColor(selectedTicket.priority)} style={{ fontSize: 12, padding: '2px 8px' }}>
                  {selectedTicket.priority.toUpperCase()}
                </Tag>
              </div>
              
              <Descriptions size="small" column={2}>
                <Descriptions.Item label="描述" span={2}>
                  {selectedTicket.description}
                </Descriptions.Item>
                <Descriptions.Item label="报告人">
                  <UserOutlined style={{ marginRight: 4, color: '#1890ff' }} />
                  {selectedTicket.reporter}
                </Descriptions.Item>
                <Descriptions.Item label="处理人">
                  <UserOutlined style={{ marginRight: 4, color: '#1890ff' }} />
                  {assignees.find(a => a.id === selectedTicket.assignee)?.name || '未分配'}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  <ClockCircleOutlined style={{ marginRight: 4, color: '#1890ff' }} />
                  {new Date(selectedTicket.createdAt).toLocaleString('zh-CN')}
                </Descriptions.Item>
                <Descriptions.Item label="更新时间">
                  <ClockCircleOutlined style={{ marginRight: 4, color: '#1890ff' }} />
                  {new Date(selectedTicket.updatedAt).toLocaleString('zh-CN')}
                </Descriptions.Item>
              </Descriptions>
            </Card>

            {/* 编辑表单 */}
            <Card 
              size="small" 
              title={
                <div style={{ 
                  fontSize: 14, 
                  fontWeight: 600, 
                  color: '#262626',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 6
                }}>
                  <EditOutlined style={{ color: '#1890ff' }} />
                  编辑工单
                </div>
              }
              style={{ 
                borderRadius: 8,
                boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02)'
              }}
            >
              <Form form={form} layout="vertical">
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      name="status"
                      label="状态"
                      rules={[{ required: true, message: '请选择状态' }]}
                    >
                      <Select>
                        <Option value="open">待处理</Option>
                        <Option value="in_progress">处理中</Option>
                        <Option value="resolved">已解决</Option>
                        <Option value="closed">已关闭</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      name="assignee"
                      label="处理人"
                    >
                      <Select placeholder="选择处理人" allowClear>
                        {assignees.map(assignee => (
                          <Option key={assignee.id} value={assignee.id}>
                            {assignee.name}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Card>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default PlatformTickets;